<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use App\Mall\OrderCreator;
use App\Models\Cart;
use App\Models\Item;
use Illuminate\Support\Facades\Auth;

class AuctionController extends ApiController
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrder()
    {
        $itemid   = $this->request->input('itemid');
        $quantity = $this->request->input('quantity');
        $pay_type = $this->request->input('pay_type');
        $shipping_type = $this->request->input('shipping_type');
        $buyer_message = $this->request->input('buyer_message');
        $address_id    = $this->request->input('address_id');

        $item = Item::find($itemid);
        if ($item) {
            $item->quantity = $quantity;
            $creator = new OrderCreator();
            $creator->shop         = $item->shop;
            $creator->items        = [$item];
            $creator->payType      = $pay_type;
            $creator->shippingType = $shipping_type;
            $creator->addressId = $address_id;
            $creator->buyerMessage = $buyer_message;

            try{
                $order = $creator->createOrder();
                return ajaxReturn(['order'=>$order]);
            }catch (\Exception $e) {
                return ajaxError($e->getCode(), $e->getMessage());
            }
        } else {
            return ajaxError(404, 'item not found');
        }
    }

    public function settlement()
    {
        $address_id = $this->request->input('address_id');
        $buyer_message = $this->request->input('buyer_message');
        $items = $this->request->input('items');

        $shops = Cart::with(['items'=>function($query){
            return $query->where('uid', $this->uid);
        }])->where('uid', $this->uid)->whereIn('itemid', $items)->groupBy('shop_id')->get(['shop_id','shop_name']);

        $orders = [];
        foreach ($shops as $shop) {
            $creator = new OrderCreator();
            $creator->shop  = $shop->shop;
            $creator->items = $shop->items;
            $creator->addressId = $address_id;
            $creator->payType = 1;
            $creator->shippingType = 1;
            $creator->buyerMessage = $buyer_message[$shop->shop_id];

            try {
                $orders[] = $creator->createOrder();
            } catch (\Exception $e){

            }
        }
        //清空购物车
        Auth::user()->cartItems()->whereIn('itemid', $items)->delete();
        return ajaxReturn(['orders'=>$orders]);
    }
}
